package Case;
import java.lang.management.ThreadInfo;
import java.util.concurrent.locks.ReentrantLock;

//Lock锁的实现
public class Lock {
    static int ticket=0;//声明100张票,设为静态属性,确保只有一份
    public static void main(String[] args) {
        java.util.concurrent.locks.Lock lock=new ReentrantLock();//创建Lock锁对象
        Runnable sales=()->{
            while (true){
                try {
                    lock.lock();
                    Thread.sleep(50);
                    Thread.yield();
                    if(ticket<100){
                        ticket++;
                        String name=Thread.currentThread().getName();
                        System.out.println(name+"售出:" + ticket + "号票");
                    }else{
                        break;
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    lock.unlock();
                }
            }
        };
    new Thread(sales,"机器1号").start();
    new Thread(sales,"机器2号").start();
    new Thread(sales,"机器3号").start();
    }
}
